package thread;

import java.util.ArrayList;
import java.util.List;

public class ReverseStr {
    public String reverseStr(String s, int k) {
        int strLength = s.length();
        List<String> result = new ArrayList<>();

        int pre = 0;

        while (pre <= strLength) {
            if (pre + 2 * k <= strLength) {
                String temp = s.substring(pre, k + pre);
                String other = s.substring(k + pre, pre + 2 * k);
                result.add(new StringBuilder(temp).reverse().toString());
                result.add(other);
            } else if (strLength - pre < k) {
                String newTemp = s.substring(pre, strLength);
                result.add(new StringBuilder(newTemp).reverse().toString());
            } else if (strLength - pre >= k && strLength - pre < 2 * k) {
                String lastTemp = s.substring(pre, pre + k);
                result.add(new StringBuilder(lastTemp).reverse().toString());
                result.add(s.substring(pre + k, strLength));
            }

            pre += 2 * k;
        }

        StringBuilder sb = new StringBuilder();
        for (String a : result) {
            sb.append(a);
        }

        return sb.toString();
    }

    public static void main(String[] args) {
        String str = "abcdefg";
        int k = 2;
        ReverseStr reverseStr = new ReverseStr();
        System.out.println(reverseStr.reverseStr(str, k));
    }
}
